package com.byd.sealmanage.util;

import com.alibaba.fastjson.JSONObject;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;
import java.util.Random;

/**
 * Md5工具类
 * @author leisen
 * @date 2019/7/15
 */
public class Md5Tool {

    /**
     * 用MD5加密字符串并返回
     */
    private static String toMd5(String s) {
        try {
            MessageDigest digest = MessageDigest.getInstance("md5");
            byte[] result = digest.digest(s.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : result) {
                int number = b & 0xff;
                String hex = Integer.toHexString(number);
                if (hex.length() == 1) {
                    sb.append("0").append(hex);
                } else {
                    sb.append(hex);
                }
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 加密-16位
     */
    public static String encrypt16(String encryptStr) {
        return Objects.requireNonNull(toMd5(encryptStr)).substring(8, 24);
    }

    /**
     * 生成盐值
     */
    public static String getSalt() {
        // 生成盐
        Random rand = new Random();
        byte[] salt = new byte[12];
        rand.nextBytes(salt);
        StringBuilder sb = new StringBuilder();
        int length = salt.length - 1;
        for (int i = 0; i <= length; i++) {
            sb.append(salt[i]);
            if (i != length) {
                sb.append(",");
            }
        }
        return sb.toString();
    }

    /**
     * MD5加密带盐值
     */
    public static String toMd5Salt(String password, String salt) {
        String[] a = salt.split(",");
        byte[] saltBytes = new byte[12];
        int val;
        for (int i = 0, len = saltBytes.length; i < len; i++) {
            val = Integer.valueOf(a[i]);
            saltBytes[i++] = (byte) val;
        }
        // 计算消息摘要
        MessageDigest m;
        StringBuilder result = new StringBuilder();
        try {
            m = MessageDigest.getInstance("MD5");
            m.update(saltBytes);
            m.update(password.getBytes(StandardCharsets.UTF_8));
            byte[] s = m.digest();
            for (byte value : s) {
                result.append(Integer.toHexString((0x000000ff & value) | 0xffffff00).substring(6));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toString();
    }


    /**
     * 密码加密
     * @return 颜值 和 加密后的密码
     * */
    public static JSONObject toEncyMd5(String password) {
        JSONObject jsonObject = new JSONObject();
        String salt = random(8);
        String newPassword = password + salt;
        String md5Password = DigestUtils.md5DigestAsHex(newPassword.getBytes());
        jsonObject.put("salt", salt);
        jsonObject.put("md5Password", md5Password);
        return jsonObject;
    }

    /**
     * 密码解密
     * @return 解密后的密码
     * */
    public static String decryptMd5 (String password, String salt) {
        String newPassword = password + salt;
        return DigestUtils.md5DigestAsHex(newPassword.getBytes());
    }

    /**
     * 生成 salt
     * */
    private static String random(int mu){
        Random random = new Random();
        String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuilder returns = new StringBuilder();
        for(int i = 0; i < mu; i ++ ){
            returns.append(chars.charAt(random.nextInt(chars.length())));
        }
        return returns.toString();
    }

}

